<?php
declare (strict_types=1);

namespace app\listener;

use app\common\model\Member;
use app\common\model\MemberInvite;
use app\common\service\TransfersServer;

class MemberInvited
{

    /**
     *
     * @param $params
     * @return void
     */
    public function handle($params)
    {
        // 被邀请人ID
        $memberIdInviteId = $params['memberIdInvite'] ?? null;

        // 邀请人ID
        // $memberId = $params['memberId'] ?? null;

        if (!is_id($memberIdInviteId)) {
            // TODO  记录错误
            return;
        }

        // 查询邀请绑定关系
        $memberIdInvite = MemberInvite::where('memberIdInvite', $memberIdInviteId)
            ->where('status', 2)
            ->find();

        // 没有邀请人绑定
        if (is_null($memberIdInvite)) {
            return;
        }

        $memberId = $memberIdInvite->memberId;

        if (!is_id($memberId)) {
            return;
        }


        // 修改状态并保存
        $memberIdInvite->status = 1;
        $memberIdInvite->save();


        // 邀请人变成推广者
        Member::where('id', $memberId)->where('isInviter', 0)->update(['isInviter' => 1]);


        // 给邀请人送 3 获客卡
        $describe = '邀请新用户奖励获客卡';
        $this->createTransfer($memberId, 3, $describe, $memberIdInviteId);

    }

    /**
     * 创建转账申请
     * @param $memberId
     * @param $card
     * @param $describe
     * @param $inviteeId
     * @return void
     */
    private function createTransfer($memberId, $card, $describe, $inviteeId)
    {
        $transferType = TRANSFER_CARD_INVITE;
        $payMethod = PAYMENT_CARD;
        $accountNumber = $memberId;
        $totalMoney = $card;
        $append = [
            'inviteeId' => $inviteeId,
        ];
        $this->getTransfersServer()->pushTransferToMember($transferType, $memberId, $payMethod, $accountNumber, $totalMoney, $describe, $append);
    }

    private function getTransfersServer(): TransfersServer
    {
        return app(TransfersServer::class);
    }

}
